using UnityEngine;
using System.Collections;

public class AutoShellShooter : MonoBehaviour
{
    public Transform firePoint; // 发射位置
    public float fireInterval = 3f; // 每轮发射的时间间隔
    public int shotsPerRound = 3; // 每轮发射几次
    public int shellsPerShot = 3; // 每次发射几个子弹
    public float shotDelay = 0.1f; // 每次之间的间隔
    public float spacing = 0.5f; // 并排子弹之间的间隔
    public float shellSpeed = 80f; // 子弹速度

    public ParticleSystem m_smokeBarrel;
    public AudioSource m_AudioSource;
    public AudioClip soundFire;

    private void Start()
    {
        StartCoroutine(FireRoutine());
    }

    private IEnumerator FireRoutine()
    {
        while (true)
        {
            for (int i = 0; i < shotsPerRound; i++)
            {
                FireShells();
                m_smokeBarrel.Play();
                m_AudioSource.PlayOneShot(soundFire);
                yield return new WaitForSeconds(shotDelay);
            }

            yield return new WaitForSeconds(fireInterval);
        }
    }

    private void FireShells()
    {
        float totalWidth = (shellsPerShot - 1) * spacing;
        for (int i = 0; i < shellsPerShot; i++)
        {
            Vector3 offset = firePoint.right * (-totalWidth / 2 + i * spacing);
            Vector3 spawnPos = firePoint.position + offset;

            GameObject shell = ShellPool.Instance.GetShell();
            shell.name = "enemyShell";
            shell.transform.position = spawnPos;
            shell.transform.rotation = Quaternion.Euler(-90f, 0f, 0f); // 固定发射角度

            Rigidbody rb = shell.GetComponent<Rigidbody>();
            if (rb != null)
            {
                rb.velocity = shellSpeed * -firePoint.forward;
            }

            // 初始化 ShellMove
            ShellMove shellMove = shell.GetComponent<ShellMove>();
            Vector3 fireDirection = -firePoint.forward;  // 注意只获取一次方向
            shellMove.Init(fireDirection, shellSpeed);
        }
    }
}
